var express = require('express');
//uuid模块 生成唯一的uuid  用来标识用户的唯一性
const { v4: uuidv4 } = require('uuid');
//m密码使用md5模块进行的加密
const md5 = require('md5');
//引入router模块 创建后端路由
var router = express.Router();
//自己封装的链接数据的模块 
var Db = require('../public/javascripts/Db')
//自己封装的 给前端返回前加一层对象，使格式统一
var endMassage = require('../public/javascripts/endMassage')
//引入验证码第三方模块
let captcha = require('svg-captcha')

//自己定义路由中间件模块  为了接口调用打印的时候多几行空行 没啥用
router.use((req, res, next) => {
  console.log("");
  console.log("");
  console.log("");
  console.log("");
  console.log("");
  next()
})


// 验证码配置信息
const options = {
  size: 4,                 // 验证码长度(显示几个字符)
  ignoreChars: '0o1i', // 验证码字符中排除 0o1i
  fontSize: 34,           // 验证码的字体大小
  width: 90,              // 验证码的宽度
  height: 40,             // 验证码的高度
  background: '#cc9966',   // 验证码的背景颜色
  color: 'red'
};

//验证码接口
var codeStr = ''
router.get('/getCaptchaCode', (req, res) => {
  let code = captcha.create(options)
  codeStr = code.text
  res.send(endMassage({ data: "验证码获取成功", code: code.data, token: md5(codeStr.toUpperCase()) }))
})
//登录注册接口  有账号 直接登录  没账号 注册 
router.get('/login', function (req, res, next) {
  let token = req.headers.token
  if (!token) res.send(endMassage({ data: "没用权限", code: 0 }))
  let { username, password, code } = req.query
  if (token != md5(code.toUpperCase())) {
    res.send(endMassage({ data: "请输入正确验证码", code: 0 }))
    return
  }
  if (!username || !password) {
    res.send(endMassage({ data: "请输入账号或密码", code: 0 }))
    return
  }
  //查询账号是否存在
  Db.DBFun(`select username,password,uuid from user where username='${username}'`, (data) => {
    if (data.length) {
      //存在验证密码是否正确
      if (data[0].password == md5(password)) {
        // console.log("密码正确");
        res.send(endMassage({ data: "登录成功", code: 1, uuidStr: data[0].uuid, token: String(username).split('').reverse().join('') + '05dda482177e9ec8d8b4a46fd9b3WIN' + new Date().getTime() }))
      }
      else res.send(endMassage({ data: "密码错误", code: 0 }))
    } else {
      //账号不存在注册
      let uuidStr = uuidv4()
      let passwordStr = md5(password)
      Db.DBFun(`insert into user(password,username,uuid) values ('${passwordStr}','${username}','${uuidStr}') `, (insertInfo) => {
        Db.DBFun(`insert into user_info(uuid) values ('${uuidStr}')`, (data) => {
          console.log(data, 'datadatadatadatadatadatadatadata');
        })
        res.send(endMassage({ data: "注册成功", code: 1, uuidStr, token: String(username).split('').reverse().join('') + '05dda482177e9ec8d8b4a46fd9b3WIN' + new Date().getTime() }))
      })

    }
  })
});
//token中间件
router.use((req, res, next) => {
  //静态文件放行
  if (req.originalUrl.includes('/images/')) {
    next()
    return
  }
  let token = req.headers.token
  if (!token) {
    console.log("===没有权限===");
    res.send(endMassage({ data: "没有权限", code: 0 }))
  }
  let massage;
  let startTime;
  let endTime = new Date().getTime()
  try {
    token ? massage = token.split('05dda482177e9ec8d8b4a46fd9b3WIN')[0].split('').reverse().join('') : massage = '未登录'; //取用户名
  } catch{
    res.send(endMassage({ data: "没有权限", code: 0 }))
  }
  console.log(`*******${new Date().toLocaleString()}有人访问接口${req.url} ===用户名是：${massage}===********`);
  token ? startTime = token.split('05dda482177e9ec8d8b4a46fd9b3WIN')[1] : 123
  if (endTime - startTime > 60 * 1000 * 60)   //一小时过期
  {
    res.send(endMassage({ data: "身份验证过期，请从新登录", code: 2 }))
    return false
  }
  // console.log("===开始判断是否有权限===");
  if (massage == '未登录') {
    console.log("===未登录 没有权限===");
    res.send(endMassage({ data: "没有权限", code: 0 }))
    return
  }
  else {
    Db.DBFun(`select username,password,uuid from user where username='${massage}'`, (data) => {
      if (data.length) {
        // console.log("===ss有权限===");
        next()
      } else {
        console.log("===没用有权限，用户名没有查到===");
        res.send(endMassage({ data: "没有权限", code: 0 }))
      }
    })
  }
})
router.use('/user', require('./indexR/changeUser'))
router.use('/pcacode', require('./indexR/PCAcode'))


module.exports = router;
